/*
版权@hehung所有，转载请申明
email：1398660197@qq.com
*/
#include <aos/aos.h>
#include <aos/cli.h>
#include <avutil/common.h>
#include <avutil/misc.h>
#include "avutil/socket_rw.h"
#include "avutil/web.h"
#include "avutil/named_straightfifo.h"

#include "app_player.h"
#include "mp3_hex.h"
#include "app_alarm.h"
#include "app_kv.h"
#include <string.h>
#include "app_main.h"
#include "app_rtc.h"


#define TAG "app_player"

#define DEFAULT_VOLUME_VALUE           (180U)

#define PLAYER_STATUS_PLAYING          (0U)
#define PLAYER_STATUS_STOPPED          (1U)

#define PLAYER_MAX_MAP_LEN             ((uint16_t)(1024*6))

typedef struct 
{
    const uint8_t *mp3_hex;
    const uint16_t mp3_len;
} s_PlayerPara;

static aos_task_t player_task_h;    /* RGB task handle */
static uint16_t player_task_cycle_ms = 100;
static uint16_t player_start_flg = 0xFFFF;
static player_t *g_player;
static uint8_t player_h = 15;    /* 需要播放的时间的小时 */
static uint8_t player_m = 10;    /* 需要播放的时间的分钟 */
static char curr_mp3_hex[PLAYER_MAX_MAP_LEN];
static uint32_t curr_mp3_len = 0;
static uint8_t player_veffect = 1;    /* 音效是否使能 */
static uint8_t player_vtime = 1;    /* 报时功能是否使能 */
static uint8_t player_button_flg = 0;    /* 是否有按钮按下的标志 */
static uint8_t player_voice_Setting_flg = 0;    /* 是否有音量设置的标志 */

static void Player_TaskEntry(void *arg);
static void Player_Welcome(void);
static void Player_PlayTime(void);
static void player_setting(uint8_t vv);
static void _player_event(player_t *player, uint8_t type, const void *data, uint32_t len);
static uint8_t Player_GetPlayerStatus(void);
static void Player_VoiveTimeCheck(void);

/* Player函数初始化 */
void Player_TaskInit(void)
{
#if (PLAYER_ENABLE == STD_ON)
	int task_s;
    int volume_v;

	/* Welcome voice */
    player_init();

    /* 从KV存储区读取音量值并设置 */
    /* 如果音量值没有被设置过，使用默认值 */
    if (1 == Kv_GetSaveStatus(KV_VOLUME_VALUE))
    {
        volume_v = Kv_ReadData(KV_VOLUME_VALUE);
        player_start_flg = volume_v;
        volume_v = (uint8_t)(((float)volume_v/100.0)*255.0+0.5);    /* 四舍五入 */
    }
    else
    {
        volume_v = DEFAULT_VOLUME_VALUE;
        player_start_flg = (uint16_t)((float)volume_v/255.0*100.0+0.5);    /* 四舍五入 *//* 表示初始化成功 */
    }

    player_setting(volume_v);

    if (1 == Kv_GetSaveStatus(KV_SOUND_EFFECT))
    {
        player_veffect = Kv_ReadData(KV_SOUND_EFFECT);
    }

    if (1 == Kv_GetSaveStatus(KV_SOUND_TIME))
    {
        player_vtime = Kv_ReadData(KV_SOUND_TIME);
    }
    

	task_s = aos_task_new_ext(&player_task_h,
								"player_task", 
								Player_TaskEntry, 
								NULL, 
								2048, 
								10);
	if (0 == task_s)
	{
		printf("APP_PLAYER Task create success\r\n");
	}
	else
	{
		printf("APP_PLAYER Task create failed\r\n");
	}
#endif
}

/* Player函数任务入口 */
static void Player_TaskEntry(void *arg)
{
    static uint8_t first_enter = 1;

    while (1) 
	{
        if (first_enter == 1)
        {
            first_enter = 0;
#if (PLAYER_ENABLE == STD_ON)
            Player_Welcome();
#endif
        }
        /* 闹钟触发 */
        if (ALARM_WARNING_ON == Alarm_GetalarmFlag())
        {
            /* 播放闹钟 */
            Player_AlarmVoice();
        }
        else
        {
            Player_VoiveTimeCheck();
            Player_Button();
            Player_Dong();
        }
        // while (Player_GetPlayerStatus() == PLAYER_STATUS_PLAYING);  /* 等待播放完成 */

		aos_msleep(player_task_cycle_ms);
    }
}

static void Player_VoiveTimeCheck(void)
{
    csi_rtc_time_t cur_t;
    static int last_hour = 0;
    static uint8_t first_enter = 1;

	/* 获取当前时间 */
	cur_t = Rtc_GetCurrentTime();
    if (1 == first_enter)
    {
        first_enter = 0;
        last_hour = cur_t.tm_hour;
    }

    /* 整点报时，支持上午九点到下午六点 */
    if ((cur_t.tm_hour != last_hour) && (cur_t.tm_min == 0))
    {
        if ((cur_t.tm_hour >= 9) && (cur_t.tm_hour <= 18))
        {
            Player_SetPlayTime(cur_t.tm_hour, 0);
            /* 播放时间 */
            Player_PlayTime();
        }
    }

    last_hour = cur_t.tm_hour;
}

/* 返回当前播放状态 */
static uint8_t Player_GetPlayerStatus(void)
{
    media_info_t minfo;
    int rc = -1;

    memset(&minfo, 0, sizeof(media_info_t));
    rc = player_get_media_info(g_player, &minfo);

    return (rc == -1) ? (PLAYER_STATUS_STOPPED) : (PLAYER_STATUS_PLAYING);
}

static void player_setting(uint8_t vv)
{
    ply_conf_t ply_cnf;

    player_conf_init(&ply_cnf);
    ply_cnf.vol_en         = 1;
    ply_cnf.vol_index      = vv;
    ply_cnf.event_cb       = _player_event;
    ply_cnf.period_num     = 12;  // 12 * 5 period_ms = 60ms
    ply_cnf.cache_size     = 32 * 1024; // web cache size

    g_player = player_new(&ply_cnf);
}

static void _player_event(player_t *player, uint8_t type, const void *data, uint32_t len)
{
//    int rc;
    UNUSED(len);
    UNUSED(data);
    UNUSED(handle);
    // LOGD(TAG, "=====%s, %d, type = %d", __FUNCTION__, __LINE__, type);

    switch (type) 
    {
        case PLAYER_EVENT_ERROR:
//            rc = player_stop(player);
                player_stop(player);
            break;

        case PLAYER_EVENT_START: 
        {
            media_info_t minfo;
            memset(&minfo, 0, sizeof(media_info_t));
//            rc = player_get_media_info(player, &minfo);
            player_get_media_info(player, &minfo);
            // LOGD(TAG, "=====rc = %d, duration = %llums, bps = %llu, size = %u", rc, minfo.duration, minfo.bps, minfo.size);
            break;
        }

        case PLAYER_EVENT_FINISH:
            player_stop(player);
            break;

        default:
            break;
    }
}

/* 播放welcome音频 */
static void Player_Welcome(void)
{
    char url[50];

    player_stop(g_player);
    while (Player_GetPlayerStatus() == PLAYER_STATUS_PLAYING);  /* 等待播放完成 */
    snprintf(url, sizeof(url), "mem://addr=%u&size=%u", (uint32_t)&welcome_mp3, welcome_mp3_len);
    player_play(g_player, url, 0);
    while (Player_GetPlayerStatus() == PLAYER_STATUS_PLAYING);  /* 等待播放完成 */
    aos_msleep(1000);
    player_stop(g_player);
}

/* 播放dong声音 */
void Player_Button(void)
{
    char url[50];

    if (1 == player_veffect)
    {
        if (player_button_flg == 1)
        {
            player_button_flg = 0;
            
            player_stop(g_player);
            while (Player_GetPlayerStatus() == PLAYER_STATUS_PLAYING);  /* 等待播放完成 */
            snprintf(url, sizeof(url), "mem://addr=%u&size=%u", (uint32_t)&button_mp3, button_mp3_len);
            player_play(g_player, url, 0);
            while (Player_GetPlayerStatus() == PLAYER_STATUS_PLAYING);  /* 等待播放完成 */
            aos_msleep(1500);
            player_stop(g_player);
        }
    }
}

/* 播放dong声音 */
void Player_Dong(void)
{
    char url[50];

    if (player_voice_Setting_flg == 1)
    {
        player_voice_Setting_flg = 0;
        
        player_stop(g_player);
        while (Player_GetPlayerStatus() == PLAYER_STATUS_PLAYING);  /* 等待播放完成 */
        snprintf(url, sizeof(url), "mem://addr=%u&size=%u", (uint32_t)&dong_mp3, dong_mp3_len);
        player_play(g_player, url, 0);
        while (Player_GetPlayerStatus() == PLAYER_STATUS_PLAYING);  /* 等待播放完成 */
        aos_msleep(1500);
        player_stop(g_player);
    }
}

/* 播放闹钟声音 */
void Player_AlarmVoice(void)
{
    char url[50];

    player_stop(g_player);
    while (Player_GetPlayerStatus() == PLAYER_STATUS_PLAYING);  /* 等待播放完成 */
    snprintf(url, sizeof(url), "mem://addr=%u&size=%u", (uint32_t)&alarm_mp3, alarm_mp3_len);
    player_play(g_player, url, 0);
    while (Player_GetPlayerStatus() == PLAYER_STATUS_PLAYING);  /* 等待播放完成 */
    aos_msleep(2000);
    player_stop(g_player);
}

/* 获取音量 
返回值：0-100*/
uint8_t Player_GetVol(void)
{
    uint8_t 
    vol;

    (void)player_get_vol(g_player, &vol);
    vol = (uint8_t)(((float)vol/255.0)*100.0+0.5);    /* 四舍五入 */
    
    return vol;
}

/* 设置音量: vol:0-100 */
void Player_SetVol(uint8_t vol)
{
    Kv_WriteData(KV_VOLUME_VALUE, vol);
    
    /* 转换0-100 to 0-255 */
    vol = (uint8_t)(((float)vol/100.0)*255.0+0.5);    /* 四舍五入 */
    
    (void)player_set_vol(g_player, vol);
}

uint16_t Player_GetStartFlg(void)
{
    return player_start_flg;
}

static void Player_PlayTime(void)
{
    char url[50];
    uint32_t i = 0;
    static const s_PlayerPara time_mp3[] = 
    {
        { zero_mp3, zero_mp3_len },
        { one_mp3, one_mp3_len },
        { two_mp3, two_mp3_len },
        { three_mp3, three_mp3_len },
        { four_mp3, four_mp3_len },
        { five_mp3, five_mp3_len },
        { six_mp3, six_mp3_len },
        { seven_mp3, seven_mp3_len },
        { eight_mp3, eight_mp3_len },
        { nine_mp3, nine_mp3_len },
        { ten_mp3, ten_mp3_len },
        { hour_mp3, hour_mp3_len },
        { min_mp3, min_mp3_len },
        { oclock_mp3, oclock_mp3_len }
    };

    if (1 == player_vtime)
    {
        
        if (player_h > 10)
        {
            for (i=0; i<time_mp3[10].mp3_len; i++)
            {
                curr_mp3_hex[i] = time_mp3[10].mp3_hex[i];
            }
            curr_mp3_len = time_mp3[10].mp3_len;  
        }
        else
        {
            curr_mp3_len = 0;
        }
        
        for (i=0; i<time_mp3[player_h%10].mp3_len; i++)
        {
            curr_mp3_hex[i+curr_mp3_len] = time_mp3[player_h%10].mp3_hex[i];
        }
        curr_mp3_len +=  time_mp3[player_h%10].mp3_len;
        for (i=0; i<time_mp3[11].mp3_len; i++)
        {
            curr_mp3_hex[i+curr_mp3_len] = time_mp3[11].mp3_hex[i];
        }
        curr_mp3_len +=  time_mp3[11].mp3_len;
        for (i=0; i<time_mp3[13].mp3_len; i++)
        {
            curr_mp3_hex[i+curr_mp3_len] = time_mp3[13].mp3_hex[i];
        }
        curr_mp3_len +=  time_mp3[13].mp3_len;

        player_stop(g_player);
        while (Player_GetPlayerStatus() == PLAYER_STATUS_PLAYING);  /* 等待播放完成 */
        snprintf(url, sizeof(url), "mem://addr=%u&size=%u", (uint32_t)curr_mp3_hex, curr_mp3_len);
        player_play(g_player, url, 0);
        while (Player_GetPlayerStatus() == PLAYER_STATUS_PLAYING);  /* 等待播放完成 */
        aos_msleep(4000);
        player_stop(g_player);
    }
}

void Player_SetPlayTime(uint8_t hour, uint8_t min)
{
	player_h = hour;
    player_m = min;
}

void Player_SetPressButtonFlg(void)
{
    player_button_flg = 1;
}

void Player_SetVoiceSettingFlg(void)
{
    player_voice_Setting_flg = 1;
}

uint8_t Player_GetVoiceEffectFlg(void)
{
    return player_veffect;
}

void Player_SetVoiceEffectFlg(uint8_t v)
{
    Kv_WriteData(KV_SOUND_EFFECT, v);
    player_veffect = v;
}

uint8_t Player_GetVoiceTimeFlg(void)
{
    return player_vtime;
}

void Player_SetVoiceTimeFlg(uint8_t v)
{
    Kv_WriteData(KV_SOUND_TIME, v);
    player_vtime = v;
}
